import os
import sys

from routers import attendance_types, employees, attendance_records, statistics

base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
log_path = os.path.join(base_path, "log.log")

# 先配置日志
import logging
import traceback

# 创建logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.ERROR)

# 创建handler用于写入日志文件
fh = logging.FileHandler(log_path, encoding='utf-8')

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

try:
    import webbrowser
    from fastapi import FastAPI, HTTPException
    from fastapi.staticfiles import StaticFiles
    from fastapi.responses import FileResponse
    from fastapi.middleware.cors import CORSMiddleware
    import uvicorn

    root_path = os.getcwd()
    sys.path.append(root_path)

    app = FastAPI()
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 注册路由
    app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
    app.include_router(attendance_types.router, prefix="/api/attendance-types", tags=["attendance_types"])
    app.include_router(attendance_records.router, prefix="/api/attendance-records", tags=["attendance_records"])
    app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])

    # 自定义StaticFiles类来处理正确的MIME类型
    class SPAStaticFiles(StaticFiles):
        async def get_response(self, path: str, scope):
            response = await super().get_response(path, scope)
            # 记录请求的路径和当前的content-type
            logger.error(f"Requesting path: {path}, current content-type: {response.headers.get('content-type')}")

            # 根据文件扩展名设置正确的MIME类型
            if path.endswith('.js'):
                response.headers['content-type'] = 'application/javascript; charset=utf-8'
            elif path.endswith('.css'):
                response.headers['content-type'] = 'text/css; charset=utf-8'
            elif path.endswith('.html'):
                response.headers['content-type'] = 'text/html; charset=utf-8'

            # 记录修改后的content-type
            logger.error(f"After modification content-type: {response.headers.get('content-type')}")
            return response


    current_dir = os.path.dirname(os.path.abspath(__file__))
    static_dir = os.path.join(current_dir, 'static')

    # 先挂载assets目录
    # app.mount("/assets", SPAStaticFiles(directory=os.path.join(static_dir, "assets")), name="assets")
    # # 挂载static目录，但不要挂载到根路径
    # app.mount("/static", SPAStaticFiles(directory=static_dir), name="static")


    @app.get("/")
    async def test():
        try:
            return FileResponse(
                os.path.join(static_dir, 'index.html'),
                media_type='text/html'
            )
        except Exception as e:
            tb = traceback.format_exc()
            logger.error(f"Error in root route: {e}\n{tb}")
            raise


    @app.get("/{page_name:path}")
    async def read_page(page_name: str):
        try:
            # 如果是API路由，跳过
            if not page_name.startswith(('certif', 'createEmail', 'home')):
                raise HTTPException(status_code=404)
            # 返回index.html以处理前端路由
            return FileResponse(
                os.path.join(static_dir, 'index.html'),
                media_type='text/html'
            )
        except Exception as e:
            tb = traceback.format_exc()
            logger.error(f"Error in page route: {e}\n{tb}")
            raise


    def start_browser():
        try:
            url = "http://localhost:8618"
            webbrowser.open_new_tab(url)
        except Exception as e:
            tb = traceback.format_exc()
            logger.error(f"Error starting browser: {e}\n{tb}")
            raise


    if __name__ == '__main__':
        try:
            # start_browser()
            uvicorn.run(app, host="localhost", port=8000)
        except Exception as e:
            tb = traceback.format_exc()
            logger.error(f"Error running server: {e}\n{tb}")
            raise

except Exception as e:
    tb = traceback.format_exc()
    logger.error(f"Initialization error: {e}\n{tb}")
    raise